/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package broadcast;

import common.function_common;
import common.global;
import hashChunk.Chunk;
import java.io.IOException;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import managerPeer.Node;

/**
 *
 * @author Chickyky
 */
public class myBroastcastListener extends Thread {
    // Set a default listener port

    private int listenerPort = 4000;
    private MulticastSocket listenerSocket = null;
    private static int MAX_PACKET_SIZE = 524288;
    private InetAddress fromAddress=null;

    //gửi riêng cho 1 peer
//    DatagramSocket datagramSocket;
//    int portPeer;
//    InetAddress inetAddressPeer;
    // Default Constructor
    public myBroastcastListener(MulticastSocket awaylsListenSocket, InetAddress inetAddress, int port) {
        this.listenerSocket = awaylsListenSocket;
        MAX_PACKET_SIZE = global.MAX_PACKET_SIZE;
        this.fromAddress = inetAddress;
        this.listenerPort = port;
    }

    private boolean isMine(DatagramPacket pk, InetAddress ia) throws UnknownHostException {
        String[] myIP = ia.getLocalHost().toString().split("/");
        System.out.println("myIP[0] = " + myIP[0]);
        System.out.println("myIP[1] = " + myIP[1]);
        System.out.println("pk.getAddress = " + pk.getAddress().toString());
        if (!pk.getAddress().toString().equals("/" + myIP[1])) {
            return false;
        } else {
            System.out.println("Nhầm hàng rồi bạn ơi!");
            return true;
        }
    }

    public void run() {
        byte[] buffer = new byte[MAX_PACKET_SIZE];
        // Create a packet to hold the data when it arrives

        DatagramPacket infoPacket =
                new DatagramPacket(buffer, MAX_PACKET_SIZE);

//        try {
//            listenerSocket.joinGroup(fromAddress);
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }

        // do an infinite loop
        while (true) {
            try {
                System.out.println("Bắt đâu lắng nghe …");
                // Setting this value to 0 causes it to be an infinite timeout
                listenerSocket.setSoTimeout(0); // = 0 la cho vo han
                listenerSocket.receive(infoPacket);
                if (isMine(infoPacket, fromAddress) == false) {
                    System.out.println("Nhận được 1 packet");
                    byte[] msg = infoPacket.getData();
                    int portPeer = infoPacket.getPort();
                    InetAddress addresPeer = infoPacket.getAddress();
                    DatagramSocket ds = new DatagramSocket(5000);// socket để liên lạc giữa 2 peer

                    //tạo 1 node mới
                    Node pc = new Node();
//                    pc.setM_ID(4);
                    pc.setM_IdAddress(addresPeer.toString().substring(1,addresPeer.toString().length() ));
                    pc.setM_Port(portPeer);
                    
                    try {
                        myPackage.Package pk = function_common.deserialize(msg);
                        switch (pk.getM_Option()) {
                            case "[$TaoDaVaoRoom]":
                                System.out.println("Nhận đc packet TaoDaVaoRoom");
                                global.nodes.updateFilePeers((Node) pc);
                                global.nodes.readFilePeers();

                                myPackage.Package pkTaoDaVaoTrongRoom = new myPackage.Package();
                                pkTaoDaVaoTrongRoom.setM_Option("[$TaoDaOTrongRoom]");
                                // gui phan hoi lai cho peer vừa vào group 
                                byte[] buff = function_common.serialize(pkTaoDaVaoTrongRoom);
                                DatagramPacket packetFeedBack = new DatagramPacket(buff, buff.length, addresPeer, portPeer);
                                ds.send(packetFeedBack);
                                break;
                            case "[$TaoDaOTrongRoom]":
                                // update list file download 
                                System.out.println("Nhận được packet TaoDaOTrongRoom");
                                global.nodes.updateFilePeers((Node) pc);
                                global.nodes.readFilePeers();
                                break;
                            case "[$AiCoChunkNay?]":
                                // file chunk and open connection UDP send file with client pere
                                //tìm xem có chunk đang share ko?
                                Chunk chunk = (Chunk) pk.getM_Data();
                                if(global.shares.checkChunkInList(chunk)){
                                    System.out.println("Tao có cái chunk này: " + chunk.getM_FileName());
                                }
                                break;
                            case "4":
                                // get list pere and send for that peer 
                                break;
                            default:
                                break;
                        }
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(myBroastcastListener.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } catch (IOException ex) {
                // Print the exception and try to keep going
                ex.printStackTrace();
            }
        }
    }
}
